const {
	http
} = require("../../../utils/apiutils")
const
	util = require("../../../utils/util")
const { input } = require('../../../utils/tools');
import { getMonday, formatNumber, formatTime, getTime } from '../../../utils/util'
const app = getApp()
var maxtimer = null
Page({
	data: {
		year: new Date().getFullYear(),
		month: new Date().getMonth() + 1,
		tabActive: 2,   // 全职2  兼职1
		sh: 0,
		item: '',
		limitTop: 0,
		limitBottom: 0,
		shs: 0,
		statusBar: 0,
		CustomBar: 0,
		canvasShow: false,
		limit: 10,
		itemHeight: 0,
		dataList: [],
		pageNo: 1,
		total: 1,
		latitude: 0,
		longitude: 0,
		action: 0,
		actionCur: {},
		type: 2,
		showPlaying: true,
		jiaonang: {}, // 胶囊数据
		today: 0,
		clickDate: 0,
		dateArr: [],
		dayArr: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
		rightshow: false,
		searchParams: {
			tag: [],
			business: ''
		},
		hy: '',
		tagList: [],
		business: []
	},
	tabChange(event) {
		let title = event.detail.title;
		let name = event.detail.name;
		this.setData({
			pageNo: 1,
			total: 1,
			dataList: [],
			type: event.detail.name,
			tabActive: event.detail.name
		})
		wx.nextTick(() => {
			this.getJob()
		})
	},
	onShareAppMessage: function () {
		var shareObj = {
			title: "分享岗位", // 默认是小程序的名称(可以写slogan等)
			path: getApp().globalData.userInfo.inviteCode ? '/pages/index/index?code=' + getApp().globalData.userInfo.inviteCode : '/pages/index/index', // 
			imageUrl: '',
			success: function (res) {
				// 转发成功之后的回调
				if (res.errMsg == 'shareAppMessage:ok') {
				}
			}
		}
		console.log("------------", shareObj);
		// 返回shareObj
		return shareObj;
	},
	onclickSearch: function () {
		wx.navigateTo({
			url: '/pages/home/pages/search/search',
		})
	},
	//检测活动距离
	scroll: function (e) {
		if (e.detail > this.data.CustomBar) {
			this.setData({
				ts: true,
			})
		} else {
			this.setData({
				ts: false,
			})
		}


		console.log("---------滑动距离---", e);
	},
	onHide(){
		clearInterval(maxtimer)
		maxtimer=null;
	},
	onUnload(){
		clearInterval(maxtimer)
		maxtimer=null;
	},
	onclickInfo: function () {
		console.log('isLogin', getApp().globalData.isLogin)
		if (!app.globalData.isLogin) {
			wx.showModal({
				title: "提示",
				content: "您还没有登录，登陆后即可查看详情",
				confirmText: "去登陆",
				success: function (res) {
					if (res.confirm) {
						wx.navigateTo({
							url: '/pages/login/login?ptype=home',
						})
					}
				}
			})
			return;
		}

		if (this.data.action == 1) {
			if (this.data.actionCur.status == 4) {
				let data = {
					id: this.data.actionCur.id,
					name: this.data.actionCur.jobName,
					workplace: this.data.actionCur.workplace,
					type: 2,
					jobId: this.data.actionCur.jobId,
				}
				wx.navigateTo({
					url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
				})

			} else if (this.data.actionCur.status == 3) {
				// console.log("-------到岗打卡-----",item);
				// this.clockIn(item.id);
				var interviewDate = "";
				var str = this.data.actionCur.interviewDate;
				if (str) {
					str = str.substring(0, 19);
					str = str.replace(/-/g, '/');
					let date = new Date(str);
					interviewDate = date.getFullYear().toString() + "-" + (date.getMonth() + 1).toString() + "-" + date.getDate().toString(); // 年
				}
				let data = {
					id: this.data.actionCur.id,
					name: this.data.actionCur.jobName,
					workplace: this.data.actionCur.workplace,
					type: 1,
					jobId: this.data.actionCur.jobId,
					interviewDate: interviewDate,
				}
				wx.navigateTo({
					url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
				})


			} else {
				wx.navigateTo({
					url: '/pages/me/pages/action2/action?type=3',
				})
			}


		} else {
			wx.navigateTo({
				url: '/pages/me/pages/action2/action?type=3',
			})
		}

		// if (this.data.action == 1) {
		//   let item = this.data.actionCur;
		//   console.log("--------", item);
		//   let data = {
		//     id: item.id,
		//     name: item.jobName,
		//     workplace: item.workplace,
		//     type: 2,
		//     jobId: item.jobId
		//   }

		//   wx.navigateTo({
		//     url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
		//   })
		// } else {
		//   wx.navigateTo({
		//     url: '/pages/me/pages/duty/duty',
		//   })
		// }


	},
	onclickCell: function (e) {
		console.log('isLogin', getApp().globalData.isLogin)
		if (!app.globalData.isLogin) {
			wx.showModal({
				title: "提示",
				content: "您还没有登录，登陆后即可查看详情",
				confirmText: "去登陆",
				success: function (res) {
					if (res.confirm) {
						wx.navigateTo({
							url: '/pages/login/login?ptype=home',
						})
					}
				}
			})
			return;
		}
		let item = e.currentTarget.dataset.item;
		// if (index % 2 == 0) {
		//   wx.navigateTo({
		//     url: '/pages/home/pages/train/train',
		//   })
		// } else {
		wx.navigateTo({
			url: '/pages/home/pages/work/work?id=' + item.id,
		})
		// }
	},

	onclickswiper: function (e) {

		let item = e.currentTarget.dataset.item;
		if (item.video) {
			wx.setStorageSync('video', JSON.stringify(item))
			wx.navigateTo({
				url: '/pages/home/pages/video/video',
			})
		} else if (item.jobImage) {
			wx.navigateTo({
				url: '../../home/pages/sq/sq?img=' + item.jobImage + '&id=' + item.eventId,
			})
		}
		else {
			wx.showToast({
				title: '暂无详细介绍',
				icon: "none",
			})
		}

	},
	getJob() {
		var data = {
			"pageNo": this.data.pageNo, //手机号码
			"pageSize": "99999", //密码
			type: this.data.type,
			date: this.data.dateArr[this.data.clickDate],
			business: this.data.searchParams.business,
			tag:this.data.searchParams.tag.join(','),
			lat:this.data.lat,
			lng:this.data.lng
		}
		console.log(this.data)
		var that = this;
		wx.showLoading({
			title: '加载中...',
		})
		http.getJob(data,
			function (res) {
				wx.hideLoading()
				console.log("------用户登录信息哦---", res);
				if (res.code == 0) {
					var pageNo = res.data.current;
					var total = res.data.pages;
					var arr = res.data.records;
					arr.forEach(element => {
						if(element.tag){
							element.tag=element.tag.split(',')
						}else{
							element.tag=[]
						}
						if (!that.data.latitude == 0) {
							// let ds = util.getDistance(that.data.latitude, that.data.longitude, element.lat, element.lng);
							// console.log("-----------", ds)
							// if (element.stationFollow == 1) {
							// 	element.dst = 0
							// }
							// else {
							// 	element.dst = ds;
							// }
							// element.ds =  ds
							// if (ds > 1) {
							// 	element.ds = ds.toFixed(1) + "Km"
							// } else {
							// 	element.ds = (ds * 1000).toFixed(0) + "m"
							// }
						} else {
							element.ds = "未知"
							element.dst = 0;
						}
					
					});
					that.setData({
						dataList: [ ...arr],
						pageNo,
						total
					})
					that.setTime()
				} else {
					wx.showToast({
						title: res.message,
						icon: "none",
					})
				}
			},
			function (err) {
				wx.hideLoading()
		})
	},
	onLoad: function (options) {
		this.setData({
			today: new Date().getDay()?new Date().getDay() - 1:6,
			clickDate: new Date().getDay()?new Date().getDay() - 1:6,
			dateArr: this.getDates()
		})
		this.data.tabActive = options.type;
		this.data.type = options.type;   // 1兼职  2全职
		this.data.lat = getApp().globalData.lat;
		this.data.lng = getApp().globalData.lng;
		console.log(getApp().globalData)
		this.isGetSetting();
		this.getBusiness()
		this.getTagList()
	},
	change: function (e) {
		this.setData({
			active: e.detail.index
		})
	},

	getclockInInfo: function () {
		var data = {
			"pageNo": 1,
			"pageSize": "10",
			"statusList": "3,4",
		}
		var that = this;
		wx.showLoading({
			title: '加载中...',
		})
		http.getregistration(data,
			function (res) {
				wx.hideLoading()
				console.log("------报名岗位列表---", res);
				if (res.code == 0) {
					var arr = res.data.records;
					// if (arr.length == 1) {
					//   that.setData({
					//     actionCur: arr[0],
					//     action: 1
					//   })
					// } else 
					if (arr.length > 0) {
						that.setData({
							actionCur: arr[0],
							action: 2,
							showPlaying: true
						})
						console.log(that.data.actionCur);
					} else {
						that.setData({
							showPlaying: false
						})
					}
				}
			},
			function (err) {
				wx.hideLoading()
			})

	},
	bindscrolltolower: function () {
		if (this.data.pageNo == this.data.total) {
			wx.showToast({
				title: '没有更多岗位了',
				icon: "none",
			})
		}
		else {
			this.data.pageNo = this.data.pageNo + 1;
			this.getJob()
		}
	},
	isGetSetting() {
		// 判断用户是否授权
		var that = this;
		wx.getLocation({
			type: 'gcj02',
			success: function (res) {
				that.data.latitude = res.latitude;
				that.data.longitude = res.longitude;
				that.getJob()
			},
			fail: function (res) {
				wx.showModal({
					title: '获取当前定位',
					content: '请打开设置，允许小程序使用位置信息',
					cancelText: '不允许',
					confirmText: '打开设置',
					success(res) {
						if (res.confirm) {
							wx.openSetting({
								withSubscriptions: true,
								success(res) {
									if (res.authSetting['scope.userLocation']) {
										that.isGetSetting()
									}
								}
							})
						}
					},
					fail(err) {
						that.getJob()
					}
				})
			},
		})
	},

	onShow: function () {
		if (app.globalData.isLogin) {
			this.getclockInInfo();
		}
	},
	onPageScroll() {

	},
	onPullDownRefresh: function () {
		this.onShow();
	},
	hasLogin(e) {
		console.log('isLogin', getApp().globalData.isLogin)
		let url = e.currentTarget.dataset.url;
		if (!app.globalData.isLogin) {
			wx.showModal({
				title: "提示",
				content: "您还没有登录，登陆后即可查看详情",
				confirmText: "去登陆",
				success: function (res) {
					if (res.confirm) {
						wx.navigateTo({
							url: '/pages/login/login',
						})
					}
				}
			})
			return;
		}
		wx.navigateTo({
			url
		})
	},
	getcapsule() {
		http.capsule({}, res => {
			if (res.code == 0) {
				this.setData({
					jiaonang: res.data
				})
			} else {
				wx.showToast({
					title: res.message,
				})
			}
		}, err => { })
	},
	showCode() {
		// wx.previewImage({
		//   urls: ['http://linghuoimage.xbbzp.com/Fpeh_EX4rVCCAZ8ZL-MAf5HfUiAF'],
		//   // urls: ['http://linghuoimage.xbbzp.com/Fo7Wv7FFziwAvH8fFDeFSw_CetA3'],
		// })
		wx.navigateTo({
			url: '/pages/tabBar/home/webview',
		})
	},

	changeDate(e) {
		this.setData({
			clickDate: e.currentTarget.dataset.index * 1
		})
		this.getJob()
	},
	setTime() {
		clearInterval(maxtimer);
		maxtimer = setInterval(() => {
			let res = [...this.data.dataList];
			res.map(item => {
				item.dao = getTime(item.asOfTime)
			})
			this.setData({
				dataList: res
			})
		}, 1000)

	},
	onClose() {
		this.setData({
			rightshow: false
		})
	},
	showRight() {
		this.setData({
			rightshow: true
		})
	},
	hy1(e) {
		// 修改行业搜索
		let key = e.currentTarget.dataset.key;
		let back = this.data.hy;
		if (back == key) {
			back = ""
		} else {
			back = key
		}
		this.setData({
			hy: back
		})

	},
	qrhy() {
		this.setData({
			['searchParams.business']: this.data.hy
		})
		this.getJob()
		this.onClose();
	},
	tagchage(e) {
		let key = e.currentTarget.dataset.key;
		let arr = this.data.searchParams.tag;
		if (arr.includes(key)) {
			arr.splice(arr.indexOf(key), 1)
		} else {
			arr.push(key)
		}
		this.setData({
			['searchParams.tag']: arr
		})
		this.getJob()
	},
	getDates() {
		var new_Date = new Date()
		console.log(new_Date)
		var timesStamp = new_Date.getTime();
		var currenDay = new_Date.getDay();
		var dates = [];
		for (var i = 0; i < 7; i++) {
			// let date = new Date(timesStamp + 24 * 60 * 60 * 1000 * (i - (currenDay + 6) % 7)).toLocaleDateString().replace(/[年月]/g, '-').replace(/[日上下午]/g, '');
			let date = formatTime(new Date(timesStamp + 24 * 60 * 60 * 1000 * (i - (currenDay + 6) % 7)));
			// date[1] = formatNumber(date[1])
			// date= date.join('-')
			dates.push(date);
		}

		return dates
	},
	getBusiness() {
		http.getBusiness({}, res => {
			this.setData({
				business: res.data
			})
		}, err => { })
	},
	getTagList(){
		http.listByType({},res=>{
			this.setData({
				tagList:res.obj
			})
		},err=>{})
	}
})

function compare(property) {
	return function (a, b) {
		var value1 = a[property];
		var value2 = b[property];
		return value1 - value2;
	}
}

